package com.hbwxz.compareprice;

import com.hbwxz.compareprice.impl.PlatformPriceStrategyImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;

/**
 * 策略上下文
 *
 * @author shenzw
 * @date 2023/12/19
 */
@Slf4j
@Component("platformStrategyContext")
public class PlatformStrategyContext {

    /**
     * 存放所有策略
     */
    private final Map<String, BiFunction<String, Object, Object>> strategyMap = new HashMap<>(16);

    /**
     * 具体的策略细节
     */
    private final PlatformPriceStrategyImpl platformPriceStrategyImpl = new PlatformPriceStrategyImpl();

    /**
     * 加载所有策略
     */
    @PostConstruct
    public void initStrategy() {
        // 淘宝
        strategyMap.put("tBaoPrice", (productName, arg2) -> platformPriceStrategyImpl.getTbPriceResult(productName));
        strategyMap.put("tBaoDiscount", (productName, arg2) -> platformPriceStrategyImpl.getTbDiscountResult(productName));

        // 京东
        strategyMap.put("jdPrice", (productName, arg2) -> platformPriceStrategyImpl.getJdPriceResult(productName));
        strategyMap.put("jdDiscount", (productName, arg2) -> platformPriceStrategyImpl.getJdDiscountResult(productName));

        // 拼多多
        strategyMap.put("pddPrice", (productName, arg2) -> platformPriceStrategyImpl.getPddPriceResult(productName));
        strategyMap.put("pddDiscount", (productName, arg2) -> platformPriceStrategyImpl.getPddDiscountResult(productName));
    }

    /**
     * 获取平台价格
     *
     * @param productName 产品名称
     * @param arg2        参数2
     * @param key         key
     * @return PriceResult
     */
    public PriceResult getPriceResult(String productName, String arg2, String key) {
        BiFunction<String, Object, Object> biFunction = strategyMap.get(key);
        if (biFunction == null) {
            // 没有找到特定的策略，则采用默认实现（一般只有加了新的类型，但是没有配置对应的处理策略才会走到这）
            log.warn("平台价格，没有配置该处理策略 key = {}，采用默认实现", key);
            return platformPriceStrategyImpl.getDefaultPriceResult(productName);
        }
        return (PriceResult) biFunction.apply(productName, arg2);
    }

    /**
     * 获取平台折扣
     *
     * @param productName 产品名称
     * @param arg2        参数2
     * @param key         key
     * @return PriceResult
     */
    public int getDiscountResult(String productName, String arg2, String key) {
        BiFunction<String, Object, Object> biFunction = strategyMap.get(key);
        if (biFunction == null) {
            // 没有找到特定的策略，则采用默认实现（一般只有加了新的类型，但是没有配置对应的处理策略才会走到这）
            log.warn("平台折扣，没有配置该处理策略 key = {}，采用默认实现", key);
            return platformPriceStrategyImpl.getDefaultDiscountResult(productName);
        }
        return (int) biFunction.apply(productName, arg2);
    }
}
